package com.example.text.diyviews

import android.app.Activity
import android.content.Context
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.RelativeLayout
import com.example.text.R
import java.util.*
import kotlin.math.log

class AutoIdentifyView : RelativeLayout {
    private lateinit var identify1: EditText
    private lateinit var identify2: EditText
    private lateinit var identify3: EditText
    private lateinit var identify4: EditText
    private lateinit var identify5: EditText
    private lateinit var identify6: EditText
    private var currentCode: String = ""

    private var lastTextComplete: LastTextComplete? = null
    private var firstTextComplete: FirstTextComplete? = null

    constructor(context: Context) : super(context) {
        init(context, null)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs)
    }

    private fun init(context: Context, attrs: AttributeSet?) {
        LayoutInflater.from(context).inflate(R.layout.view_auto_identify, this)
        identify1 = findViewById(R.id.identify1)
        identify2 = findViewById(R.id.identify2)
        identify3 = findViewById(R.id.identify3)
        identify4 = findViewById(R.id.identify4)
        identify5 = findViewById(R.id.identify5)
        identify6 = findViewById(R.id.identify6)
        setIdentify()
        setThirdlyLoseFocusable()
    }

    /**
     * 让后三个失去焦点,第一个得到焦点
     */
    private fun setThirdlyLoseFocusable() {
        loseFocusable(identify1, true)
        loseFocusable(identify2, false)
        loseFocusable(identify3, false)
        loseFocusable(identify4, false)
        loseFocusable(identify5, false)
        loseFocusable(identify6, false)
    }

    private fun loseFocusable(editText: EditText, focusable: Boolean) {
        editText.isFocusable = focusable
        editText.isFocusableInTouchMode = focusable
    }

    /**
     * 设置4个验证码 自动跳到下一个输入框 并且回调第一个和最后一个输入输入完成后的状态 记录输入
     */
    private fun setIdentify() {
        val editTexts = listOf(identify1, identify2, identify3, identify4,identify5,identify6)
        editTexts.forEachIndexed { index, editText ->
            addTextChangeListener(editText, if (index < editTexts.size - 1) editTexts[index + 1] else null)
        }
    }

    private fun addTextChangeListener(currentEdit: EditText, nextEdit: EditText?) {
        currentEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
//                LogUtils.debugInfo("before=${s.toString()}")
                Log.d("TAG", "before=${s.toString()}")
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
               // LogUtils.debugInfo("changed=${s.toString()}")
                Log.d("TAG", "changed=${s.toString()}")
            }

            override fun afterTextChanged(editable: Editable) {
                val str = editable.toString()
               // LogUtils.debugInfo(str)
                Log.d("TAG", str)

                if (currentEdit.text.toString().length >= 1) {
                    currentCode += currentEdit.text.toString()

                    if (currentEdit == identify1) { //如果当前是第一输入框，输入完回调
                        firstTextComplete?.firstComplete(str)
                    }

                    //输入完成一个就让其失去焦点
                    currentEdit.isSelected = true
                    loseFocusable(currentEdit, false)

                    nextEdit?.let {
                        it.isSelected = false
                        loseFocusable(it, true)
                        it.requestFocus()
                    } ?: run {
                        //输入完成回调
                        lastTextComplete?.lastComplete(currentCode)
                    }
//                    LogUtils.debugInfo("currentCode=$currentCode")
                    Log.d("TAG", "currentCode=$currentCode")
                }
            }
        })
    }

    /**
     * 清除验证码，初始化验证码框状态，弹出键盘
     */
    fun initIdentifyBoxKeyboard(activity: Activity) {
        clearContent()
        setThirdlyLoseFocusable()
        setShowKeyboard(activity)
    }

    /**
     * 弹出键盘
     */
    fun setShowKeyboard(activity: Activity) {
        identify1?.let {
            KeyBoardUtil.showInput(it, activity)
        }
    }

    interface LastTextComplete {
        fun lastComplete(str: String)
    }

    interface FirstTextComplete {
        fun firstComplete(str: String)
    }

    /**
     * 回调当前的最后一个输入框完成
     */
    fun getLastTextComplete(lastTextComplete: LastTextComplete) {
        this.lastTextComplete = lastTextComplete
    }

    /**
     * 回调当前的第一个输入框完成
     */
    fun getFirsTextComplete(firstTextComplete: FirstTextComplete) {
        this.firstTextComplete = firstTextComplete
    }

    /**
     * 设置红色错误状态
     */
    fun setErrorStatus() {
        //设置红色背景框
        setBackResource(identify1, R.drawable.shape_cursor)
        setBackResource(identify2, R.drawable.shape_cursor)
        setBackResource(identify3, R.drawable.shape_cursor)
        setBackResource(identify4, R.drawable.shape_cursor)
        setBackResource(identify5, R.drawable.shape_cursor)
        setBackResource(identify6, R.drawable.shape_cursor)
//        setBackResource(identify4, R.drawable.cipher_choose_red)
        //清除内容
        clearContent()
        //第一个获取焦点
        loseFocusable(identify1, true)
    }

    private fun clearContent() {
        currentCode = ""
        identify1.text?.clear()
        identify2.text?.clear()
        identify3.text?.clear()
        identify4.text?.clear()
        identify5.text?.clear()
        identify6.text?.clear()
    }

    private fun setBackResource(identify: EditText, reId: Int) {
        identify.setBackgroundResource(reId)
    }

    /**
     * 初始化状态 加粗字体 不限输入为数字
     */
    fun initDeerCipher() {
//        setBackResource(identify1, R.drawable.shape_cursor)
        setBackResource(identify1, R.drawable.shape_cursor)
        setBackResource(identify2, R.drawable.shape_cursor)
        setBackResource(identify3, R.drawable.shape_cursor)
        setBackResource(identify4, R.drawable.shape_cursor)
        setBackResource(identify5, R.drawable.shape_cursor)
        setBackResource(identify6, R.drawable.shape_cursor)

        identify1.inputType = InputType.TYPE_CLASS_TEXT
        identify2.inputType = InputType.TYPE_CLASS_TEXT
        identify3.inputType = InputType.TYPE_CLASS_TEXT
        identify4.inputType = InputType.TYPE_CLASS_TEXT
        identify5.inputType = InputType.TYPE_CLASS_TEXT
        identify6.inputType = InputType.TYPE_CLASS_TEXT
    }

    fun getCurrentCode(): String = currentCode

    private fun setCurrentCode(currentCode: String) {
        this.currentCode = currentCode
    }
}